package com.analysis.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.time.Duration;

/**
 * HTTP客户端超时配置类
 * 为Spring AI的HTTP请求设置超时时间
 * 兼容Spring Boot 3.4.0和Spring AI 1.0.0-M6
 */
@Configuration
public class HttpClientTimeoutConfig {

    /**
     * 配置RestTemplate超时时间和字符编码
     * 连接超时：5分钟，读取超时：5分钟，字符编码：UTF-8
     */
    @Bean
    public RestTemplate restTemplate() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(300000); // 连接超时：5分钟
        factory.setReadTimeout(300000);    // 读取超时：5分钟
        
        RestTemplate restTemplate = new RestTemplate(factory);
        
        // 设置字符编码为UTF-8
        restTemplate.getMessageConverters().stream()
                .filter(converter -> converter instanceof StringHttpMessageConverter)
                .forEach(converter -> {
                    StringHttpMessageConverter stringConverter = (StringHttpMessageConverter) converter;
                    stringConverter.setDefaultCharset(StandardCharsets.UTF_8);
                });
        
        return restTemplate;
    }

    /**
     * 配置RestTemplateBuilder超时时间
     * 使用Spring Boot 3.4.0兼容的Duration方法
     */
    @Bean
    public RestTemplateBuilder restTemplateBuilder() {
        // 使用Duration.ofMillis()替代已弃用的Duration.ofMinutes()
        return new RestTemplateBuilder()
                .connectTimeout(Duration.ofMillis(300000))  // 连接超时：5分钟 = 300000毫秒
                .readTimeout(Duration.ofMillis(300000));    // 读取超时：5分钟 = 300000毫秒
    }
}
